<template>
  <demo-content :title="title">
    <p></p>
    <div style="position: relative">
      <label style="position: absolute; left: 20px; top: 20px">
        <stroke-color-selector v-model:value="strokeColor" />
      </label>
      <label style="position: absolute; left: 250px; top: 20px">
        <span style="margin-right: 5px">Guidewires:</span>
        <input type="checkbox" v-model="guidewires" />
      </label>
      <button
        style="position: absolute; left: 400px; top: 20px; cursor: pointer"
        @click="eraseAll"
      >
        Erase all
      </button>

      <!-- box-shadow 的 4 个参数分别为 x偏移/y偏移/高斯模糊值/颜色 -->
      <canvas
        ref="canvasRef"
        width="600"
        height="400"
        style="box-shadow: 5px 5px 10px gray"
      ></canvas>
    </div>
  </demo-content>
</template>

<script setup lang="ts">
import { onMounted, ref, watchEffect } from "vue";
import { Point, drawGrid, rect, DrawingAssist } from "./utils";
import { StrokeColorSelector } from "./components";

const title = "橡皮筋式线条";
// 指定组件上的属性
defineOptions({ title });

let ctx: CanvasRenderingContext2D;

const canvasRef = ref<HTMLCanvasElement>();
const strokeColor = ref("red");
const guidewires = ref(true);

function eraseAll() {
  rect.clear(ctx);
  ctx.beginPath();
  drawGrid(ctx, { stepx: 10, stepy: 10 });
}

onMounted(() => {
  const canvas = canvasRef.value!;
  ctx = canvas.getContext("2d")!;
  drawGrid(ctx, { stepx: 10, stepy: 10 });

  function draw(ctx: CanvasRenderingContext2D, startPos: Point, endPos: Point) {
    ctx.beginPath();
    const { x, y } = startPos;
    ctx.moveTo(x, y);
    const { x: x2, y: y2 } = endPos;
    ctx.lineTo(x2, y2);
    ctx.strokeStyle = strokeColor.value;
    ctx.stroke();
  }
  const drawingAssist = DrawingAssist.create(ctx).setDrawingCallee(draw);
  watchEffect(() => {
    if (guidewires.value) {
      drawingAssist.useGuidewires();
    } else {
      drawingAssist.disuseGuidewires();
    }
  });
});
</script>

<style src="./default.css" scoped></style>
